import sys

from naoqi import ALBroker

from commandLineHandler import CommandLineHandler
from recordWav import RecordWavModule
from audioSoundProcessing import SoundProcessingModule
from controlNao import ControlNaoModule 
from commandParser import CommandParser
from aaltoASRInterface import AaltoASRInterface


import ConfigParser

config = ConfigParser.ConfigParser()
config.read('../configuration files/recognition_config.ini')


#These constants could be later read from config file
NAO_PASSWORD = config.get("NAO", "NAO_PASSWORD")
PATH_TO_NAO_RECORDS = config.get("NAO", "PATH_TO_NAO_RECORDS")
AUDIO_FILENAME = config.get("NAO", "AUDIO_FILENAME")

CONVERTED_AUDIO_FILE = config.get("PC", "CONVERTED_AUDIO_FILE")
PATH_TO_COMPUTER_AUDIO = config.get("PC", "PATH_TO_COMPUTER_AUDIO")
PATH_TO_COMMAND_CONFIG = config.get("PC", "PATH_TO_COMMAND_CONFIG")
PATH_TO_AALTOASR_DECODER = config.get("PC", "PATH_TO_AALTOASR_DECODER")

COMMAND_TIME = config.getint("AUDIO", "COMMAND_TIME") #recording time for command
AUDIO_FREQUENCY = config.getint("AUDIO", "AUDIO_FREQUENCY")
ACTIVE_CHANNELS = [item=="True" for item in config.get("AUDIO", "ACTIVE_CHANNELS").split()] 
THRESHOLD_FOR_RMS = config.getint("AUDIO", "THRESHOLD_FOR_RMS")

CONFIDENCE_THRESHOLD = config.getint("AALTO_ASR", "CONFIDENCE_THRESHOLD")



      
def createModules():
    global soundProcessor
    global naoController
    global recorder
    global commandLineHandler
    global commandParser
    global aaltoASRInterface
   
 
    soundProcessor = SoundProcessingModule("soundProcessor", IP, THRESHOLD_FOR_RMS)
    naoController = ControlNaoModule("naoController", IP)
    recorder = RecordWavModule("recorder", IP, AUDIO_FREQUENCY, ACTIVE_CHANNELS, PATH_TO_NAO_RECORDS+AUDIO_FILENAME)
    commandLineHandler = CommandLineHandler(IP, NAO_PASSWORD)
  
    commandParser = CommandParser(CONFIDENCE_THRESHOLD)
    commandParser.readCommandConfig(PATH_TO_COMMAND_CONFIG)
    #print("Commands " + str(commandParser.commands))
    
    aaltoASRInterface = AaltoASRInterface(PATH_TO_AALTOASR_DECODER)
 
     

def startRecognition():
    print "Recognition started!"   
     
    while(True):
        print "Ready for next command!"
            
        #Wait for loud sound before starting to record
        if not soundProcessor.startProcessing(): #will return false in case of keyboard interrupt aka ctrl+c
            return
        
        #Nao blinks as a signal for starting to record command
        naoController.blinkEyes(0.5)
                            
        #Record .wav file on NAO
        print "Starting record"
        recorder.recordWav(COMMAND_TIME)
        
        #print "Transfer audio file to PC"
        #Transfer .wav file to computer
        if not commandLineHandler.transfer_file(PATH_TO_NAO_RECORDS + AUDIO_FILENAME, PATH_TO_COMPUTER_AUDIO):
            print "ERROR WHILE TRANSFERRING FILE TO PC"
            continue
        
        if not commandLineHandler.convert_file_to_16kHz(PATH_TO_COMPUTER_AUDIO+ "/" + AUDIO_FILENAME, PATH_TO_COMPUTER_AUDIO+ "/" + CONVERTED_AUDIO_FILE):
            continue
        
        #print "Send file to AaltoASR"
        #Get recognition result
        resultFromAaltoASR = aaltoASRInterface.analyzeFile(PATH_TO_COMPUTER_AUDIO+ "/" + CONVERTED_AUDIO_FILE)

        #print "Parse result from AaltoASR"
        command = commandParser.parseStringFromAaltoASR(resultFromAaltoASR)
  
        #print "Send command to Nao"
        if(command):
            naoController.executeControl(command[0], command[1])
        else:
            print("Parser did not find corresponding Nao command!")
            naoController.blinkEyesErrorResponse()
        
           

if __name__ == '__main__':
    #IP= "10.100.45.87"
    if len(sys.argv) < 2:
        print "Usage <robot ip>"
    else:
        IP = sys.argv[1]
        
        try:
            # Create new Python Broker
            pythonBroker = ALBroker("pythonBroker","0.0.0.0",9999, IP,9559)
            
            # Create needed modules
            createModules()

            # Ready start recognition, let's go!
            startRecognition()
            
            # Recognition stopped, shutdown AaltoASR interface
            aaltoASRInterface.closeInterface()
            
            pythonBroker.shutdown()
            
        except Exception as e:
            print "Error occured ", e
            pythonBroker.shutdown()
            
       
        
        '''
        Time requirements:
        ~ 4s for initialization 
        ~ 1s for transferring audio file to PC (48 kHz 2 seconds .wav-file)
        ~ 3.5s for getting result from AaltoASR (2 seconds audio file) 
        '''
 
    
       
        
        
